'use strict';
const Controller = require('egg').Controller;

class TopicController extends Controller {
  async addTopic() {
    const { ctx } = this;
    const { topicImg, topicTitle } = ctx.request.body;
    const userId = ctx.user.userId;
    const newTopic = {
      topicImg: JSON.stringify(topicImg),
      topicTitle,
      userId,
    };
    await ctx.service.topic.insertTopic(newTopic);
    ctx.returnBody(200, '发帖成功');
  }

  async topicDetail() {
    const { ctx } = this;
    const { topicId } = ctx.request.query;
    const topicDetail = await ctx.service.topic.topicDetailHandler(topicId);
    ctx.returnBody(200, '成功', topicDetail);
  }

  async friendsTopicList() {
    const { ctx } = this;
    const userId = ctx.user.userId;
    // 1. 获取 已关注人
    const follower = await ctx.service.follow.findFollower({
      followedId: userId,
      status: 1,
    });
    const followList = follower.map(item => item.userId);
    followList.push(userId);

    // 2. 按按时间顺序获取用户发送的topic
    const Op = this.app.Sequelize.Op;
    const topics = await ctx.service.topic.queryTopicList({
      userId: {
        [Op.in]: followList,
      },
    });

    // 3. 连表查询每个topic的userInfo
    const topicList = [];
    for (const topic of topics) {
      const item = await ctx.service.topic.topicDetailHandler(topic.topicId);
      topicList.push(item);
    }

    topicList && ctx.returnBody(200, '获取成功', topicList);
  }

  async addDiscuss() {
    const { ctx } = this;
    const { topicId, replayContent } = ctx.request.body;
    const { userId } = ctx.user;
    const user = await this.service.user.getUserByUserId(userId);
    const newDiscuss = {
      topicId,
      replayContent,
      replayName: user.username,
      userId,
    };

    const discuss = await ctx.service.topic.insertDiscuss(newDiscuss);

    discuss && ctx.returnBody(200, '评论发表成功');
    !discuss && ctx.returnBody(400, '网络异常，请重试');
  }

  async giveThumbsUp() {
    const { ctx } = this;
    const { topicId, status } = ctx.request.body;
    const { userId } = ctx.user;
    const topicStatus = {
      topicId,
      userId,
      status,
    };

    // 点赞create 取消点赞 update
    const query = {
      topicId,
      userId,
    };

    await ctx.service.topic.addThumbsUp(query, topicStatus);
    ctx.returnBody(200, '更新成功', {
      status: +status,
    });
  }
}

module.exports = TopicController;
